//
//  ActivitySearchViewController.swift
//  iModern
//
//  Created by Ralf on 15/6/1.
//  Copyright (c) 2015年 com.starlooking. All rights reserved.
//

import UIKit

class ActivitySearchViewController: TableViewController
{
    var activites      = NSMutableArray()
    let max            = 10
    var offset         = 0
    var end            = false
    let articleManager = ArticleManager()
    var textField: UITextField!
    let screen         = UIScreen.mainScreen().bounds

    override func viewDidLoad()
    {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "refresh:", name: "Refresh Market", object: nil)


        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()

        self.tableView.registerNib(UINib(nibName: "ActivitySearchViewSearchCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "SEARCH")
        self.tableView.registerNib(UINib(nibName: "ActivityViewAdvertisingCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ADVERTISING")
        self.tableView.registerNib(UINib(nibName: "ActivityViewArticleCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ARTICLE")

        self.initBackButton()

        self.navigationItem.title = "搜索"
    }

    override func viewWillAppear(animated: Bool)
    {
        super.viewWillAppear(animated);
        MobClick.beginLogPageView("ActivitySearchView")

    }

    override func viewWillDisappear(animated: Bool)
    {
        super.viewWillDisappear(animated);
        MobClick.endLogPageView("ActivitySearchView")
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return activites.count + 1
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        if indexPath.row <= 0
        {
            let cell
            = tableView.dequeueReusableCellWithIdentifier("SEARCH", forIndexPath: indexPath) as! ActivitySearchViewSearchCell
            textField = cell.getTextField()
            cell.getButton().addTarget(self, action: "search:", forControlEvents: .TouchUpInside)
            return cell
        }
        else
        {
            let activity = activites[indexPath.row - 1] as! NSMutableDictionary

            let article = activity["article"] as! NSDictionary
            let type    = article["type"] as! String

            if type == "Article"
            {
                let cell
                = tableView.dequeueReusableCellWithIdentifier("ARTICLE", forIndexPath: indexPath) as! ActivityViewArticleCell
                cell.setData(activity)
                return cell
            }
            else
            {
                let cell
                = tableView.dequeueReusableCellWithIdentifier("ADVERTISING", forIndexPath: indexPath) as! ActivityViewAdvertisingCell
                cell.setData(activity)
                return cell
            }
        }
    }


    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        if indexPath.row > 0
        {
            let activity = activites[indexPath.row - 1] as! NSMutableDictionary
            let aritcle  = activity["article"] as! NSDictionary
            let type     = aritcle["type"] as! String

            if type == "Article"
            {
                let controller = ArticlePageViewController()
                controller.activity = activity
                self.pushViewController(controller)
            }
            else
            {
                let controller = AdvertisingPageViewController()
                controller.activity = activity
                self.pushViewController(controller)
            }
        }
    }

    func loadData()
    {
        if end
        {
            return
        }

        let rs = articleManager.searchByMessage(textField.text, max: max, offset: offset)

        if verifyResutSet(rs)
        {
            if !rs.isEmpty()
            {
                activites.addObjectsFromArray(rs.toMutableArray() as [AnyObject])
                offset = activites.count

                tableView.reloadData()
            }
            else
            {
                end = true
            }
        }
    }

    @IBAction override func reloadData(sender: AnyObject!)
    {
        end = false
        offset = 0
        activites.removeAllObjects()
        loadData()
//        tableView.reloadData()
        super.reloadData(sender)
    }

    @IBAction func search(sender: AnyObject)
    {
        self.view.endEditing(true)
        reloadData(sender)
    }

    @IBAction func refresh(sender: AnyObject)
    {
        self.reloadData(sender)
        self.tableView.reloadData()
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        if indexPath.row <= 0
        {
            return 50
        }
        else
        {
            let message       = activites.objectAtIndex(indexPath.row - 1).objectForKey("article")?.objectForKey("message") as! NSString
            let messageHeight = sizeOfText(message).height
            return screen.size.width + 100 + messageHeight + 10
        }
    }
    func sizeOfText(text: NSString) -> CGSize
    {
        let paragraphStyle = NSMutableParagraphStyle()
        
        paragraphStyle.lineHeightMultiple = 16
        paragraphStyle.maximumLineHeight = 20
        paragraphStyle.minimumLineHeight = 20
        
        //        paragraphStyle.firstLineHeadIndent = 20
        paragraphStyle.alignment = .Left
        
        let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(14),
            NSParagraphStyleAttributeName: paragraphStyle,
            NSForegroundColorAttributeName: UIColor.darkGrayColor()]
        
        let frame = CGSizeMake(screen.size.width, screen.size.height)
        let options = unsafeBitCast(NSStringDrawingOptions.TruncatesLastVisibleLine.rawValue | NSStringDrawingOptions.UsesLineFragmentOrigin.rawValue |
            NSStringDrawingOptions.UsesFontLeading.rawValue,
            NSStringDrawingOptions.self)
        let size  = text.boundingRectWithSize(frame, options: options, attributes: attributes, context: nil)
        return size.size
    }
}
